package middleware

import (
	"encoding/base64"
	"gin/service/userService"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

func JwtAuthMiddleware() gin.HandlerFunc {

	return func(c *gin.Context) {
		auth := c.GetHeader("Auth")
		if auth == "" {
			c.Next()
			return
		}

		var uid int64
		var channel string

		authTrue, err := base64.StdEncoding.DecodeString(auth)
		if err == nil {
			arr := strings.Split(string(authTrue), "|")
			if len(arr) == 2 {
				auth = arr[0]
				uid, _ = strconv.ParseInt(arr[1], 10, 64)
			}
			if len(arr) == 3 {
				auth = arr[0]
				uid, _ = strconv.ParseInt(arr[1], 10, 64)
				channel = arr[2]
			}
		}

		bol, msg := userService.CheckToken(uid, auth, channel)
		if bol {
			c.Set("uid", uid)
			c.Set("token", auth)
			c.Set("channel", channel)
		} else {
			c.Set("msg", msg)
		}

		c.Next()

	}
}
